
package com.crcc.common.util;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UtilFile {
	public final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();

	static {
		FILE_TYPE_MAP.put("1a45", "mkv"); // mkv
		FILE_TYPE_MAP.put("4156", "avi"); // AVI
		FILE_TYPE_MAP.put("2e52", "rm"); // Real Media
		FILE_TYPE_MAP.put("0000", "mpg/mp4"); // MP4
		FILE_TYPE_MAP.put("6d6f", "mov"); // QuickTime
		FILE_TYPE_MAP.put("3026", "asf"); // Windows Media
	}

	private static final Log logger = LogFactory.getLog(UtilFile.class);

	protected static final int BUFFER_SIZE = 16 * 1024;
	public static final String fileSeparator = System.getProperty("file.separator");
	public static final String lineSeparator = System.getProperty("line.separator");

	/**
	 * 依据头部信息（绝对路径）判断是否为（支持的）视频文件（true：是，false：否）
	 *
	 * @param filePath
	 * @return
	 */
	public static boolean isVideo(String filePath) {
		return FILE_TYPE_MAP.get(getFileHeader(filePath)) != null;
	}

	/**
	 * 依据头部信息（输入流）判断是否为（支持的）视频文件（true：是，false：否）
	 *
	 * @param is
	 * @return
	 */
	public static boolean isVideo(InputStream is) {
		return FILE_TYPE_MAP.get(getFileHeader(is)) != null;
	}

	/**
	 * 获得文件头部字符串
	 *
	 * @param src
	 * @return
	 */
	private static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 根据文件路径获取文件头信息
	 *
	 * @param filePath
	 *            文件路径
	 * @return 文件头信息
	 */
	private static String getFileHeader(String filePath) {
		FileInputStream is = null;
		String value = null;
		try {
			is = new FileInputStream(filePath);
			byte[] b = new byte[2];
			is.read(b, 0, b.length);
			value = bytesToHexString(b);
		} catch (Exception e) {
			logger.error(e.toString());
			return null;
		} finally {
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					logger.error(e.toString());
				}
			}
		}
		return value;
	}

	/**
	 * 根据文件路径获取文件头信息
	 *
	 * @param is
	 * @return 文件头信息
	 */
	private static String getFileHeader(InputStream is) {
		String value = null;
		try {
			byte[] b = new byte[2];
			is.read(b, 0, b.length);
			value = bytesToHexString(b);
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return value;
	}

	/**
	 * 创建多级目录
	 *
	 * @param dir
	 */
	public static boolean mkdirs(String dir) {
		File file = new File(dir);
		if (file.exists() && file.isDirectory()) {
            return true;
        }
		return file.mkdirs();
	}

	public static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	public static void list(List<String> lst, String path) {
		File f = new File(path);
		if (f.isDirectory()) {
			lst.add(f.getAbsolutePath() + fileSeparator);
			String[] dirs = f.list();
			for (int i = 0; dirs != null && i < dirs.length; i++) {
				list(lst, f.getAbsolutePath() + fileSeparator + dirs[i]);
			}
		}
		if (f.isFile()) {
			lst.add(f.getAbsolutePath());
		}
	}

	// 流转化成文件,continuingly=true 续传
	public static void inputStreamToFile(InputStream is, File file, Boolean continuingly) throws Exception {
		InputStream inputSteam = is;
		BufferedInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new BufferedInputStream(inputSteam);
			fos = new FileOutputStream(file, continuingly);
			int f;
			while ((f = fis.read()) != -1) {
				fos.write(f);
			}
			fos.flush();
			fos.close();
			fis.close();
			inputSteam.close();
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (fos != null) {
                fos.close();
            }
			if (fis != null) {
                fis.close();
            }
			if (inputSteam != null) {
                inputSteam.close();
            }
		}
	}

	// 流转化成文件
	public static void copyInputStreamToFile(InputStream in, File file) throws Exception {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			out.flush();
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (out != null) {
                out.close();
            }
			if (in != null) {
                in.close();
            }
		}

	}

	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			logger.info("所删除的文件不存在！");
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param myfiles
	 * @param upload_path
	 *            ：上传文件的相对路径
	 * @return
	 */
	public static String uploadFile(HttpServletRequest request, @RequestParam MultipartFile[] myfiles, String upload_path) throws Exception {
		String fileName = null;
		for (MultipartFile myfile : myfiles) {
			if (myfile.getSize() > 0) {
				String[] exts = myfile.getOriginalFilename().split("\\.");
				fileName = System.currentTimeMillis()+ "." + exts[1];
				String realPath = request.getSession().getServletContext().getRealPath(upload_path);
				File file = new File(realPath + File.separator + fileName);
				file.mkdirs();
				myfile.transferTo(file);
			}
		}
		return fileName;
	}

	public static void main(String[] args) throws Exception {
		new File("D:\\file\\temp_photos\\20160507\\5e4bea05-d72b-4fd4-ba6f-a86d02953951.jpg").delete();

	}

	public static String readToString(String fileName) {
		String encoding = "UTF-8";
		File file = new File(fileName);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

	public void test(HttpServletResponse response){
		ServletOutputStream out = null;
		File file = new File("C:\\Users\\yujq\\Desktop\\统计.xlsx");
		try{
			out = response.getOutputStream();
			// 告诉浏览器用什么软件可以打开此文件
			response.setHeader("content-Type", "application/vnd.ms-excel");
			// 下载文件的默认名称
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("啦啦啦测试吧","UTF-8") + ".xls");
			//编码
			response.setCharacterEncoding("UTF-8");
			FileInputStream inputStream = new FileInputStream(file);
			// 读取文件流
			int len = 0;
			byte[] buffer = new byte[1024 * 10];
			while ((len = inputStream.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			out.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
